<template>
  <div>
    <div class="list-div body-content padding-bottom-48"
         :class="listCode === listTypeList.order ? itemList.length === 1 ? 'order-list-div' : 'backcolor-color-grey' : ''">
      <van-pull-refresh v-model="isRefreshLoading" @refresh="onRefresh">
        <van-list v-model="listLoading" ref="vanListRef"
                  :finished="finished"
                  offset="80"
                  @load="onLoad"
        >
          <template v-if="listCode === listTypeList.todo">
            <todo-item v-for="(item, i) of itemList" :key="'todoItem' + i"
                       ref="todoItemRef" :list-item-code="listItemCode" :item="item"
                       v-on:todoItemCompleteEvent="todoComplete"
                       v-on:todoItemRefreshEvent="onRefresh"
            ></todo-item>
            <van-action-sheet v-model="todo.ifShowEdit">
              <todo-textarea :title="todo.addTitle"
                             v-on:todoTextareaLeftEvent="todo.ifShowEdit = false"></todo-textarea>
            </van-action-sheet>
          </template>
          <template v-if="listCode === listTypeList.product">
            <product-item :list-item-code="listItemCode"
                          v-for="(item, i) of itemList"
                          :item="item"
                          :key="'productListItem' + i "
                          v-on:productNumRefreshEvent = "onRefresh"
            ></product-item>
          </template>
          <template v-if="listCode === listTypeList.search">
            <product-item :list-item-code="listItemCode"
                          v-for="(item, i) of itemList"
                          :item="item"
                          :key="'productSearchListItem' + i "
            ></product-item>
          </template>
          <template v-if="listCode === listTypeList.order">
            <order-item :list-item-code="listItemCode"
                        v-for="(item, i) of itemList"
                        :item="item"
                        :key="'orderListItem' + i "
                        v-on:orderNumRefreshEvent = "onRefresh"
            ></order-item>
          </template>
          <template v-if="listCode === listTypeList.report"></template>
          <template v-if="listCode === listTypeList.cycle">
            <profile-item :list-code="listTypeList.cycle"
                          :list-item-code="listItemCode"
                          v-for="(item, i) of itemList"
                          :item="item"
                          :key="'reportCycleListItem' + i "
            ></profile-item>
          </template>
          <template v-if="listCode === listTypeList.performance">
            <profile-item :list-code="listTypeList.performance"
                          :list-item-code="listItemCode"
                          v-for="(item, i) of itemList"
                          :item="item"
                          :key="'reportPerformanceListItem' + i "
            ></profile-item>
          </template>
          <template v-if="listCode === listTypeList.profile">
            <profile-item :list-code="listTypeList.profile"
                          :list-item-code="listItemCode"
                          v-for="(item, i) of itemList"
                          :item="item"
                          :key="'reportPerformanceListItem' + i "
            ></profile-item>
          </template>
        </van-list>
      </van-pull-refresh>
    </div>
    <div class="tip-div" v-if="todo.ifShowTip">
      <img class="icon-16" src="@/static/icon/16px_done_circle.png" alt=""/>
      <span class="margin-left-4 paragraph-p2-light">待办事项已完成</span>
      <span class="paragraph-p3-heavy tip-div-cancel" @click="todoTipCancel">撤销</span>
    </div>
  </div>
</template>

<script>
import {ActionSheet, PullRefresh, Toast} from "vant";
import {
  changeTaskStatusToDone,
  getActiveStaff,
  getAllOrders,
  getAllProducts,
  getInactiveStaff, getPersonalSummaryCurrentDuration, getPersonalSummaryFromStart, getProductByCode, searchProduct,
  viewAllTasks
} from "@/request/api"
import ProductItem from '@/components/product/item'
import TodoItem from '@/components/todo/item'
import OrderItem from "@/components/order/item"
import ProfileItem from "@/components/profile/item"
import TodoTextarea from '@/components/todo/textarea'

export default {
  name: "ItemList",
  components: {
    [ActionSheet.name]: ActionSheet,
    [PullRefresh.name]: PullRefresh,
    OrderItem,
    ProductItem,
    TodoItem,
    TodoTextarea,
    ProfileItem,
  },
  props: {
    limitPage:  {type: Number, default: () => 0},
    searchValue: {type: String, default: () => ''},
    productCode: {type: String, default: () => ''},
    listCode: {type: Number, default: () => this.GLOBAL.listType.todo},
    listItemCode: {type: Number, default: () => this.GLOBAL.listItemType.todo.waiting},
  },
  data() {
    return {
      isRefreshLoading: false,
      listLoading: false,
      finished: false,
      pageNum: 0,
      maxPage: 1,
      pageSize: 30,
      listTypeList: this.GLOBAL.listType,
      listItemTypeList: this.GLOBAL.listItemType,
      itemList: [],
      todo: {
        ifShowEdit: false,
        ifShowTip: false,
        addTitle: '新增',
      },
      product: {
        choose: {
          searchValue: ''
        },
      },
    }
  },
  mounted() {},
  methods: {
    onLoad() {
      this.listLoading = true
      if (!this.finished) {
        this.pageNum = this.pageNum + 1
        this.getList()
        this.listLoading = false
        this.finished = this.pageNum === this.maxPage
      }
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false
      this.itemList = []
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.isRefreshLoading = true
      this.pageNum = 0
      this.onLoad()
      this.$emit("itemNumRefreshEvent")
      this.isRefreshLoading = false
    },
    async getList() {
      await this.getItemList()
    },
    getItemList() {
      return new Promise(() => {
        switch (this.listCode) {
          case this.listTypeList.todo:
            this.getTodoList()
            break
          case this.listTypeList.product:
            this.getProductList()
            break
          case this.listTypeList.search:
            this.getProductSearchList()
            break
          case this.listTypeList.order:
            this.getOrderList()
            break
          case this.listTypeList.profile:
            this.getProfileList()
            break
          case this.listTypeList.cycle:
            this.getReportCycleList()
            break
          case this.listTypeList.performance:
            this.getReportPerformanceList()
            break
        }
      })
    },
    getTodoList() {
      let todoListItemType = this.listItemTypeList.todo
      let todoStatus = this.listItemCode === todoListItemType.waiting ? '待办' :
          this.listItemCode === todoListItemType.done ? '已完成' : ''
      const limitSize = this.limitPage * this.pageSize
      if (limitSize === 0 || this.itemList.length < limitSize) {
        this.$loading.show()
        viewAllTasks({
          task_status: todoStatus,
          page_number: this.pageNum,
          size: limitSize === 0 ? 50 : 10,
        }).then(res => {
          const {State, Data} = res
          if (State) {
            const {last_page, data} = Data
            this.maxPage = last_page
            this.itemList = this.$baseJS.addAll(this.itemList, data)
          }
          this.$loading.close()
        }).catch( () => { this.$loading.close() })
      }
    },
    getProductList() {
      this.$loading.show()
      let productListItemType = this.listItemTypeList.product
      if (this.listItemCode === productListItemType.choose) {
        if (this.productCode) {
          this.getProductByCode()
        } else {
          this.searchProduct('正式入库')
        }
      } else {
        let productStatus = this.listItemCode === productListItemType.toStorage ? '拟入库' :
            this.listItemCode === productListItemType.storage ? '正式入库' :
                this.listItemCode === productListItemType.removed ? '已下架' : ''
        getAllProducts({product_status: productStatus, page_number: this.pageNum, size: this.pageSize}).then(res => {
          const {State, Data, Msg} = res
          if (State) {
            const {last_page, data} = Data
            this.maxPage = last_page
            this.itemList = this.$baseJS.addAll(this.itemList, data)
          } else { Toast(Msg) }
          this.$loading.close()
        }).catch( () => { this.$loading.close() })
      }

    },
    getProductSearchList() {
      let productListItemType = this.listItemTypeList.product
      let productStatus = this.listItemCode === productListItemType.toStorage ? '拟入库' :
          this.listItemCode === productListItemType.storage ? '正式入库' :
              this.listItemCode === productListItemType.removed ? '已下架' : ''
      if (this.productCode) {
        this.getProductByCode()
      } else {
        this.searchProduct(productStatus)
      }
    },
    searchProduct(productStatus) {
      searchProduct({ key_word: this.searchValue, page_number: 1, size: 1000, product_status: productStatus,}).then(res => {
        const {State, Msg, Data} = res
        if (State) {
          const {data} = Data
          this.maxPage = 1
          this.itemList = data
        } else { Toast(Msg) }
        this.$loading.close()
      }).catch( () => { this.$loading.close() })
    },
    getProductByCode() {
      getProductByCode({product_code: this.productCode}).then(res => {
        const {State, Msg, Data} = res
        if (State) {
          this.maxPage = 1
          this.itemList = Data
        } else { Toast(Msg) }
      })
    },
    getOrderList() {
      this.$loading.show()
      let orderListItemType = this.listItemTypeList.order
      let orderStatus = this.listItemCode === orderListItemType.payment ? '有余款' :
          this.listItemCode === orderListItemType.verification ? '待核款' :
              this.listItemCode === orderListItemType.shipment ? '待发货' :
                  this.listItemCode === orderListItemType.pickup ? '待自提' :
                      this.listItemCode === orderListItemType.shipped ? '已发货' :
                          this.listItemCode === orderListItemType.settlement ? '寄卖待结' :
                              this.listItemCode === orderListItemType.completed ? '已完成' : ''
      getAllOrders({
        order_status: orderStatus,
        page_number: this.pageNum,
        size: this.pageSize,
      }).then(res => {
        const {State, Data} = res
        if (State) {
          const {last_page, data} = Data
          this.maxPage = last_page
          this.itemList = this.$baseJS.addAll(this.itemList, data)
        }
        this.$loading.close()
      }).catch( () => { this.$loading.close() })
    },
    getReportCycleList() {
      let reportCycleListItemType = this.listItemTypeList.report.cycle
      if (this.listItemCode === reportCycleListItemType.current) {
        this.getReportCycleCurrentList()
      }
      if (this.listItemCode === reportCycleListItemType.total) {
        this.getReportCycleTotalList()
      }
    },
    getReportCycleCurrentList() {
      this.$loading.show()
      getPersonalSummaryCurrentDuration().then(res => {
        const {State, Data} = res
        if (State) {
          this.maxPage = 1
          let reportCycleCurrentTitle;
          for (let i = 0; i < Data.length; i++) {
            const {user_id, sales_name, head_image, total_retail_value, start_date, end_date} = Data[i]
            let saleItem = { id: user_id, avatar: head_image, name: sales_name, money: total_retail_value, isFirst: i === 0}
            this.itemList.push(saleItem)
            reportCycleCurrentTitle = start_date + '-' + end_date
          }
          this.$emit('reportCycleCurrentTitleEvent', reportCycleCurrentTitle)
        }
        this.$loading.close()
      }).catch( () => { this.$loading.close() })
    },
    getReportCycleTotalList() {
      this.$loading.show()
      getPersonalSummaryFromStart().then(res => {
        const {State, Data} = res
        if (State) {
          this.maxPage = 1
          let reportCycleTotalTitle;
          for (let i = 0; i < Data.length; i++) {
            const {user_id, sales_name, head_image, total_retail_value, start_date, end_date} = Data[i]
            let saleItem = { id: user_id, avatar: head_image, name: sales_name, money: total_retail_value, isFirst: i === 0}
            this.itemList.push(saleItem)
            reportCycleTotalTitle = start_date + '-' + end_date
          }
          this.$emit('reportCycleTotalTitleEvent', reportCycleTotalTitle)
        }
        this.$loading.close()
      }).catch( () => { this.$loading.close() })
    },
    getReportPerformanceList() {
      let reportPerformanceListItemType = this.listItemTypeList.report.performance
      if (this.listItemCode === reportPerformanceListItemType.current) {
        this.getReportPerformanceCurrentList()
      }
      if (this.listItemCode === reportPerformanceListItemType.total) {
        this.getReportPerformanceTotalList()
      }
    },
    getReportPerformanceCurrentList() {},
    getReportPerformanceTotalList() {},
    getProfileList() {
      let profileListItemType = this.listItemTypeList.profile
      if (this.listItemCode === profileListItemType.onJob) {
        this.getProfileOnJobList()
      }
      if (this.listItemCode === profileListItemType.outJob) {
        this.getProfileOutJobList()
      }
    },
    getProfileOnJobList() {
      this.$loading.show()
      getActiveStaff({
        page_number: this.pageNum,
        size: 6,
      }).then(res => {
        const { State, Data } = res
        if (State) {
          const { data, last_page } = Data
          data.forEach(onJobProfile => {
            const {id, name, head_image_url, phone_number} = onJobProfile
            let saleItem = { id: id, avatar: head_image_url, name: name, phone: phone_number }
            this.maxPage = last_page
            this.itemList.push(saleItem)
          })
        }
        this.$loading.close()
      }).catch( () => { this.$loading.close() })
    },
    getProfileOutJobList() {
      this.$loading.show()
      getInactiveStaff({
        page_number: this.pageNum,
        size: 6,
      }).then(res => {
        const { State, Data } = res
        if (State) {
          const { data, last_page } = Data
          data.forEach(onJobProfile => {
            const {id, name, head_image_url, phone_number} = onJobProfile
            let saleItem = { id: id, avatar: head_image_url, name: name, phone: phone_number }
            this.maxPage = last_page
            this.itemList.push(saleItem)
          })
        }
        this.$loading.close()
      }).catch( () => { this.$loading.close() })
    },
    todoComplete(id) {
      this.todo.ifShowTip = true
      let timer = setInterval(() => {
        if (this.todo.ifShowTip) {
          changeTaskStatusToDone({pathParam: id}).then(res => {
            const {State} = res
            if (State) {
              this.todo.ifShowTip = false
              this.$emit('itemNumRefreshEvent')
            }
            clearInterval(timer)
          }).catch(() => {clearInterval(timer)})
        }
      }, 5000)
    },
    todoTipCancel() {
      this.todo.ifShowTip = false
      this.onRefresh()
    },
  },
}
</script>

<style scoped>
.list-div {
  display: flex;
  position: relative;
}
.tip-div {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 4px 8px;

  position: absolute;
  height: 30px;
  left: 97px;
  top: 70vh;

  background: #D6F5ED;
  border-radius: 4px;
}

.tip-div-cancel {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 2px 8px;
  margin-left: 8px;
  height: 22px;
  background: #FFFFFF;
  border-radius: 8px;
}

.padding-bottom-48 {
  padding-bottom: 64px;
}
</style>